package com.itbuka.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itbuka.canal.config.RabbitConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CanalEventListener
public class GoodsListener {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 监听product表的数据变化
     *
     * @param eventType 当前操作数据库的类型
     * @param rowData   当前操作数据库的数据
     */
    @ListenPoint(schema = "itbuka_goods", table = "goods_product")
    public void productUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        if (eventType == CanalEntry.EventType.UPDATE) {
            //改变之前的数据
            List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
            //改变之后的数据
            List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
            Map<String, String> map = new HashMap<>();
            for (CanalEntry.Column column : beforeColumnsList) {
                if (column.getName().equals("status")) {
                    map.put("before", column.getValue());
                }
            }
            for (CanalEntry.Column column : afterColumnsList) {
                if (column.getName().equals("status")) {
                    map.put("after", column.getValue());
                }
                if (column.getName().equals("id")) {
                    map.put("id", column.getValue());
                }
            }
            if (Integer.parseInt(map.get("before")) == 0 && Integer.parseInt(map.get("after")) == 1) {
                rabbitTemplate.convertAndSend(RabbitConfig.GOODS_EXCHANGE, RabbitConfig.GOODS_QUEUE, map.get("id"));
            }

            if (Integer.parseInt(map.get("before")) == 1 && Integer.parseInt(map.get("after")) == 0) {
                rabbitTemplate.convertAndSend(RabbitConfig.GOODS_DOWN_EXCHANGE, RabbitConfig.GOODS_DOWN_QUEUE, map.get("id"));
            }
        }
    }
}